package com.caszx.chargingpile.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.fastjson.JSONException;
import com.app.base.adapter.BaseClickRecyclerAdapter;
import com.app.base.adapter.BaseHeadFootAdapter;
import com.app.base.app.BaseTopBarDelayActivity;
import com.app.base.app.BaseTopBarNetActivity;
import com.app.jsonparse.JSONParse;
import com.app.utils.DiskUser;
import com.app.utils.DividerGridItemDecoration;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.entity.EntityMessage;
import com.caszx.chargingpile.entity.EntitySubRecord;
import com.caszx.chargingpile.holder.reservate.ReservateIngHolder;
import com.caszx.chargingpile.holder.user.MessageHolder;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.SnackbarHelp;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;

public class UserMessageActivity extends BaseTopBarNetActivity {


    private RecyclerView mRecyclerView;
    private BaseHeadFootAdapter<EntityMessage> mRecyclerAdapter;
    private PtrClassicFrameLayout ptrFrame;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCenterTitle("系统消息");
    }

    @Override
    protected void onLoad() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_MEESSAGE)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        if(ptrFrame!=null){
                            ptrFrame.refreshComplete();
                        }
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        if(ptrFrame!=null){
                            ptrFrame.refreshComplete();
                        }
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"), null);
                                showErrorView();
                            } else {
                                try {
                                    List<EntityMessage> datas = JSONParse.parseArray(response.optString("messageRecord"), EntityMessage.class);
                                    showContentView();
                                    mRecyclerAdapter.setDatas(datas);
                                } catch (JSONException e) {
                                    showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected View initOnloadedView() {
        View view = getLayoutInflater().inflate(R.layout.common_refrash_recyclerview, null);
        initPtrFrameLayout(view);
        initRecyclerView(view);
        return view;
    }



    private void initPtrFrameLayout(View view) {
        ptrFrame = (PtrClassicFrameLayout) view .findViewById(R.id.ptr_classic_frameLayout);
        ptrFrame.setLastUpdateTimeRelateObject(this);
        ptrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                onLoad();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame,
                                             View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrame,
                        mRecyclerView, header);
            }
        });
    }

    private void initRecyclerView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mRecyclerView.setBackgroundResource(R.color.gray3);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        DividerGridItemDecoration decoration = new DividerGridItemDecoration(this);
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerAdapter = new BaseHeadFootAdapter<>(R.layout.item_user_message, MessageHolder.class);
        mRecyclerView.setAdapter(mRecyclerAdapter);
        mRecyclerAdapter
                .setOnItemClickListener(new BaseClickRecyclerAdapter.OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        EntityMessage message = mRecyclerAdapter.getItems().get(position);
                        if(message.readMark == EntityMessage.MESG_UNREAD){
                            readMessage(message.messageId,position,false);
                        }

                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_txt,menu);
        MenuItem menuItem = menu.findItem(R.id.menutxt);
        menuItem.setTitle("一键已读");
        //menu.add(Menu.NONE,  Menu.FIRST , 0, "一键已读");//.setIcon(R.drawable.setting);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(getBaseLoadedView(true) == null)return true;
        if(hasUnReadMessge()){
            showProgressDialog("一键读取");
            readMessage(null,-1,true);
        }else{
            SnackbarHelp.showSnackbarMsg(UserMessageActivity.this,"暂无可读消息");
        }

        return super.onOptionsItemSelected(item);
    }

    private boolean hasUnReadMessge(){
        if(mRecyclerAdapter.getItems() == null) return false;
        for (EntityMessage message:mRecyclerAdapter.getItems()){
           if(EntityMessage.MESG_UNREAD ==message.readMark){
               return  true;
           }
        }
        return false;
    }

    private void readMessage(String id, final  int position,final  boolean isReadAll){
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        if(!isReadAll){
            params.put("messageId", id);
        }

        String url = isReadAll?ConstantUrl.URL_USER_READ_ALL_MEESSAGE:ConstantUrl.URL_USER_READ_MEESSAGE;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        if(isReadAll){
                            dissmissProgressDialog();
                            SnackbarHelp. showSnackbarMsg(UserMessageActivity.this,getResources().getString(R.string.error_network));
                        }
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"), null);
                                SnackbarHelp. showSnackbarMsg(UserMessageActivity.this,resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    if(isReadAll){
                                        for (EntityMessage message:mRecyclerAdapter.getItems()){
                                            message.readMark = EntityMessage.MESG_READED;
                                        }
                                        mRecyclerAdapter.notifyDataSetChanged();
                                    }else{
                                        mRecyclerAdapter.getItems().get(position).readMark = EntityMessage.MESG_READED;
                                        mRecyclerAdapter.notifyItemChanged(position);
                                    }
                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(UserMessageActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });
    }

}
